package com.coolwalker.common.utils;

import java.security.MessageDigest;

public class MD5Utils {

    /**
     * 生成MD5
     *
     * @param message 入参
     * @return 编码后MD5数据
     */
    public static String genMD5(String message) {
        try {
            String MD5_DIGEST = "MD5";
            String CHARSET_NAME = "UTF-8";
            MessageDigest md = MessageDigest.getInstance(MD5_DIGEST);
            byte[] messageByte = message.getBytes(CHARSET_NAME);
            // 获得MD5字节数组,16*8=128位
            byte[] md5Byte = md.digest(messageByte);
            // 转换为16进制字符串
            return bytesToHex(md5Byte);
        } catch (Exception e) {
            throw new RuntimeException("MD5 digest failed, cause by " + e.getMessage());
        }
    }

    /**
     * 二进制转十六进制
     *
     * @param bytes 编码节
     * @return 十六进结果
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexStr = new StringBuilder();
        int num;
        for (byte aByte : bytes) {
            num = aByte;
            if (num < 0) {
                num += 256;
            }
            if (num < 16) {
                hexStr.append(0);
            }
            hexStr.append(Integer.toHexString(num));
        }
        return hexStr.toString().toUpperCase();
    }
}
